/**
 * Copyright (C) 2007-2011 JUG Events Team <info@jugevents.org>
 *
 * This file is part of JUG Events Web Application.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package it.jugpadova.controllers;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.MemoryAppender;
import it.jugpadova.blo.EventBo;
import it.jugpadova.blo.JugBo;
import it.jugpadova.blo.SpeakerBo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/admin/*.html")
public class AdminController {

    @Resource
    private JugBo jugBo;
    @Resource
    private EventBo eventBo;
    @Resource
    private SpeakerBo speakerBo;
    private static final Logger logger =
            LoggerFactory.getLogger(AdminController.class);

    @RequestMapping
    public ModelAndView index(HttpServletRequest req,
            HttpServletResponse res) {
        return new ModelAndView("admin/index", null);
    }

    @RequestMapping
    public ModelAndView logs(HttpServletRequest req,
            HttpServletResponse res) {
        if ("true".equals(req.getParameter("clean"))) {
            MemoryAppender.getInstance().clearLogs();
        }

        if ("error".equals(req.getParameter("test"))) {
            logger.error("sample error message");
        }
        if ("warn".equals(req.getParameter("test"))) {
            logger.warn("sample warn message");
        }
        List<ILoggingEvent> logLines = MemoryAppender.getInstance().getLogLines();
        String log = colourLog(logLines);

        Map params = new HashMap();
        params.put("log", log);
        return new ModelAndView("admin/logs", params);
    }

    @RequestMapping
    public ModelAndView conf(HttpServletRequest req,
            HttpServletResponse res) {
        return new ModelAndView("admin/conf", null);
    }

    @RequestMapping
    public ModelAndView spring(HttpServletRequest req,
            HttpServletResponse res) {
        return new ModelAndView("admin/spring", null);
    }

    private String colourLog(List<ILoggingEvent> logLines) {
        StringBuilder sb = new StringBuilder();
        for (ILoggingEvent line : logLines) {
            String cssClass;
            switch (line.getLevel().levelInt) {
                case Level.ERROR_INT:
                    cssClass = "text-error";
                    break;
                case Level.DEBUG_INT:
                    cssClass = "muted";
                    break;
                case Level.WARN_INT:
                    cssClass = "text-warning";
                    break;
                case Level.INFO_INT:
                    cssClass = "text-info";
                    break;
                default:
                    cssClass = "";
            }
            sb.append("<p class=\"").append(cssClass).append("\">").append(line.
                    getFormattedMessage()).append("</p>");
        }
        return sb.toString();
    }

    @RequestMapping
    public ModelAndView updateJugList(HttpServletRequest req,
            HttpServletResponse res) throws Exception {
        jugBo.updateJugList(null);
        return new ModelAndView("redirect:/admin/logs.html");
    }

    @RequestMapping
    public ModelAndView regenerateLuceneIndexes(HttpServletRequest req,
            HttpServletResponse res) throws Exception {
        eventBo.regenerateLuceneIndexes();
        speakerBo.regenerateLuceneIndexes();
        logger.info("Regenerated the Lucene indexes");
        return new ModelAndView("redirect:/admin/logs.html");
    }
}
